<template>
  <view class="container">
    <block v-if="isload">
      <form @submit="formSubmit">
        <view class="form-content" v-for="(item, index) in og" :key="index">
          <!-- 商品信息 -->
          <view class="form-item1">
            <view class="product flex">
              <view class="img">
                <image :src="item.pic"></image>
              </view>
              <view class="info flex1">
                <view class="f1">{{ item.name }}</view>
                <view class="f2">已购：{{ item.ggname }}</view>
                <view class="f3">￥{{ item.sell_price }}</view>
              </view>
            </view>
          </view>

          <!-- 评分 -->
          <view class="form-item2 flex flex-y-center">
            <view class="label">您的打分</view>
            <view class="i-rate" @touchmove="handleTouchMove(index, $event)">
              <input type="text" name="score" :value="item.score" class="i-rate-hide-input"></input>
              <view v-for="(star, starIndex) in 5" :key="starIndex" class="i-rate-star"
                :class="(starIndex < item.score ? 'i-rate-current' : '')" :data-index="starIndex"
                @tap="handleClick(index, starIndex)">
                <image v-if="starIndex < item.score" src="/static/img/star2.png"></image>
                <image v-else src="/static/img/star.png"></image>
              </view>
              <view class="i-rate-text"></view>
            </view>
          </view>

          <!-- 评价标签 -->
          <view class="form-item2 flex flex-y-center">
            <view class="label">评价标签</view>
            <view class="tags">
              <view v-for="(tag, tagIndex) in tags" :key="tag.id" class="tag" @tap="toggleTag(index, tag)" :style="{
                backgroundColor: item.selectedTags.includes(String(tag.id)) ? t('color2') : ''
              }">
                {{ tag.name }}
              </view>
            </view>
          </view>

          <!-- 评价内容 -->
          <view class="form-item3 flex-col">
            <view class="label">您的评价</view>
            <textarea placeholder="输入您的评价内容" placeholder-style="color:#ccc;" name="comment" :value="item.comment"
              style="height:130rpx" @input="handleInput(index, $event)" :disabled="item.isCommented">
            </textarea>
          </view>

          <!-- 上传图片 -->
          <view class="form-item4 flex-col">
            <view class="label">上传图片</view>
            <view id="content_picpreview" class="flex" style="flex-wrap:wrap;padding-top:10rpx">
              <view v-for="(pic, picIndex) in item.content_pic" :key="picIndex" class="layui-imgbox">
                <view class="layui-imgbox-close" @tap="removeimg(index, picIndex)" v-if="!item.isCommented">
                  <image src="/static/img/ico-del.png"></image>
                </view>
                <view class="layui-imgbox-img">
                  <image :src="pic" @tap="previewImage" :data-url="pic" mode="widthFix"></image>
                </view>
              </view>
              <view class="uploadbtn"
                :style="'background:url(' + static_url + '/static/img/shaitu_icon.png) no-repeat 30rpx;background-size:40rpx 40rpx;background-color:#F3F3F3;'"
                @tap="uploadimg(index)" v-if="!item.isCommented && item.content_pic.length < 5">
              </view>
            </view>
          </view>
        </view>
        <button class="btn" form-type="submit" :style="{ background: t('color1') }" v-if="isEditMode">确定</button>
      </form>
    </block>
    <loading v-if="loading"></loading>
    <dp-tabbar :opt="opt"></dp-tabbar>
    <popmsg ref="popmsg"></popmsg>
  </view>
</template>
<script>
var app = getApp();

export default {
  data() {
    return {
      opt: {},
      loading: false,
      isload: false,
      pre_url: app.globalData.pre_url, static_url: app.globalData.static_url,
      og: [], // 商品列表
      tags: [], // 标签列表
      isEditMode: false, // 是否编辑模式
    };
  },

  onLoad: function (opt) {
    this.opt = app.getopts(opt);
    this.getdata();
    this.getCommentTags();
  },

  methods: {
    // 获取数据
    getdata: function () {
      var that = this;
      var ogid = that.opt.ogid;
      that.loading = true;
      app.get('Order/commentAll', {
        id: ogid
      }, function (res) {
        that.loading = false;
        if (res.status == 200) {
          // 初始化每个商品的数据
          that.og = res.data.og.map(item => {
            return {
              ...item,
              score: 0, // 默认评分
              content_pic: [], // 默认上传的图片
              comment: '', // 默认评价内容
              selectedTags: [], // 默认选择的标签
              isCommented: false, // 标记是否已评价
            };
          });

          // 如果有评论数据，回显到对应的商品中
          if (res.data.comment && res.data.comment.length > 0) {
            res.data.comment.forEach(comment => {
              // 找到对应的商品
              const targetItem = that.og.find(item => item.id === comment.ogid);
              if (targetItem) {
                targetItem.score = comment.score; // 回显评分
                targetItem.comment = comment.content; // 回显评价内容
                targetItem.content_pic = comment.content_pic ? comment.content_pic.split(',') : []; // 回显图片
                targetItem.selectedTags = comment.tags ? comment.tags.split(',').map(String) : []; // 回显标签（将字符串转为字符串数组）
                targetItem.isCommented = true; // 标记为已评价
                console.log('评论标签数据:', comment.tags); // 打印评论标签数据
                console.log('转换后的 selectedTags:', targetItem.selectedTags); // 打印转换后的 selectedTags
              }
            });
          }

          // 检查是否有未评价的商品
          const hasUncommentedItem = that.og.some(item => !item.isCommented);
          that.isEditMode = hasUncommentedItem; // 如果有未评价的商品，设置为可编辑模式
          console.log('isEditMode:', that.isEditMode); // 打印 isEditMode 的值
          console.log('商品评价状态:', that.og.map(item => item.isCommented)); // 打印每个商品的评价状态
        } else {
          app.error(res.msg);
        }
        that.isload = true; // 数据加载完成
      });
    },

    // 获取评价标签
    getCommentTags: function () {
      var that = this;
      var ogid = that.opt.ogid;
      that.loading = true;
      app.get('Shop/getCommentTags', {
        proid: ogid
      }, function (res) {
        that.loading = false;
        if (res.status == 200) {
          that.tags = res.data;
        } else {
          app.error(res.msg);
        }
      });
    },

    // 评分点击事件
    handleClick: function (index, starIndex) {
      console.log('评分点击事件触发:', index, starIndex); // 打印日志
      if (!this.isEditMode || this.og[index].isCommented) return;
      this.og[index].score = starIndex + 1;
    },

    // 评分滑动事件
    handleTouchMove: function (index, e) {
      console.log('评分滑动事件触发:', index); // 打印日志
      if (!this.isEditMode || this.og[index].isCommented) return;
      var clientWidth = uni.getSystemInfoSync().windowWidth;
      if (!e.changedTouches[0]) return;
      var movePageX = e.changedTouches[0].pageX;
      var space = movePageX - 150 / 750 * clientWidth;
      if (space <= 0) return;
      var starwidth = 60 / 750 * clientWidth;
      var setIndex = Math.ceil(space / starwidth);
      setIndex = setIndex > 5 ? 5 : setIndex;
      this.og[index].score = setIndex;
    },

    // 标签点击事件
    toggleTag: function (index, tag) {
      console.log('标签点击事件触发:', index, tag); // 打印日志
      if (!this.isEditMode || this.og[index].isCommented) return;
      const selectedTags = this.og[index].selectedTags;
      const tagId = String(tag.id); // 将 tag.id 转为字符串

      if (selectedTags.includes(tagId)) {
        // 移除已选中的标签
        this.og[index].selectedTags = selectedTags.filter((id) => id !== tagId);
      } else {
        // 添加新选中的标签
        this.og[index].selectedTags = [...selectedTags, tagId];
      }
      console.log('当前选中的标签:', this.og[index].selectedTags); // 打印选中的标签
    },

    // 输入评价内容
    handleInput: function (index, e) {
      console.log('输入评价内容事件触发:', index); // 打印日志
      if (this.og[index].isCommented) return;

      // 使用 Vue.set 确保数据更新是响应式的
      this.$set(this.og[index], 'comment', e.detail.value);

      console.log('当前评价内容:', this.og[index].comment); // 打印当前评价内容
    },

    // 上传图片
    uploadimg: function (index) {
      console.log('上传图片事件触发:', index); // 打印日志
      if (this.og[index].isCommented) return;
      var that = this;
      app.chooseImage(function (urls) {
        for (var i = 0; i < urls.length; i++) {
          that.og[index].content_pic.push(urls[i]);
        }
      }, 5);
    },

    // 删除图片
    removeimg: function (index, picIndex) {
      console.log('删除图片事件触发:', index, picIndex); // 打印日志
      if (this.og[index].isCommented) return;
      this.og[index].content_pic.splice(picIndex, 1);
    },

    // 提交表单
    formSubmit: function (e) {
      var that = this;
      var ogid = that.opt.ogid;
      console.log('提交前的 og 数据:', that.og);
      var contents = that.og.map(item => {
        return {
          content: item.comment,
          content_pic: item.content_pic.join(','),
          score: item.score,
          ogid: item.id,
          tags: item.selectedTags.join(','),
        };
      });

      var submitData = {
        contents: contents,
        id: ogid,
      };

      app.showLoading('提交中');
      app.post('Order/commentAll', submitData, function (data) {
        app.showLoading(false);
        app.success(data.msg);
        setTimeout(function () {
          app.goback(true);
        }, 2000);
      });
    },
  },
};
</script>
<style>
.form-content {
  width: 94%;
  margin: 10rpx 3%;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  background: #fff;
  overflow: hidden
}

.form-item1 {
  width: 100%;
  background: #fff;
  padding: 8rpx 20rpx;
}

.form-item1 .label {
  width: 100%;
  height: 40rpx;
  line-height: 40rpx
}

.product {
  width: 100%;
  background: #fff;
}

.product .info {
  padding-left: 20rpx;
  padding-right: 20rpx;
}

.product .info .f1 {
  width: 95%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 24rpx
}

.product .info .f2 {
  color: #a4a4a4;
  font-size: 24rpx
}

.product .info .f3 {
  color: #ff0d51;
  font-size: 28rpx
}

.product image {
  width: 100rpx;
  height: 100rpx
}

.form-item2 {
  width: 100%;
  background: #fff;
  padding: 0rpx 20rpx;
  margin-top: 1px
}

.form-item2 .label {
  width: 150rpx;
  height: 40rpx;
  line-height: 40rpx
}

.form-item3 {
  width: 100%;
  background: #fff;
  padding: 8rpx 20rpx;
  margin-top: 1px
}

.form-item3 .label {
  width: 100%;
  height: 60rpx;
  line-height: 60rpx
}

.form-item3 textarea {
  width: 100%;
  border: 1px #dedede solid;
  border-radius: 10rpx;
  padding: 10rpx;
  height: 80rpx;
}


.form-item4 {
  width: 100%;
  background: #fff;
  padding: 10rpx 20rpx;
  margin-top: 1px
}

.form-item4 .label {
  width: 150rpx;
}

/*.form-item4 image{ width: 100rpx; height: 100rpx;background:#eee;margin-right:6rpx}
.form-item4 .imgbox{height:100rpx}*/


.btn {
  height: 80rpx;
  line-height: 80rpx;
  width: 90%;
  margin: 0 auto;
  border-radius: 50rpx;
  margin-top: 50rpx;
  color: #fff;
  font-size: 30rpx;
  font-weight: bold
}

.i-rate {
  margin: 0;
  padding: 0;
  display: inline-block;
  vertical-align: middle;
}

.i-rate-hide-input {
  display: none
}

.i-rate-star {
  display: inline-block;
  color: #e9e9e9;
  padding: 0 10rpx
}

.i-rate-star image {
  width: 50rpx;
  height: 50rpx
}

.i-rate-current {
  color: #f5a623
}

.i-rate-text {
  display: inline-block;
  vertical-align: middle;
  margin-left: 6px;
  font-size: 14px
}

.layui-imgbox {
  margin-right: 16rpx;
  margin-bottom: 10rpx;
  font-size: 24rpx;
  position: relative;
}

.layui-imgbox-close {
  position: absolute;
  display: block;
  width: 32rpx;
  height: 32rpx;
  right: -16rpx;
  top: -16rpx;
  color: #999;
  font-size: 32rpx;
  background: #fff
}

.layui-imgbox-close image {
  width: 100%;
  height: 100%
}

.layui-imgbox-img {
  display: block;
  width: 100rpx;
  height: 100rpx;
  padding: 2px;
  border: #d3d3d3 1px solid;
  background-color: #f6f6f6;
  overflow: hidden
}

.layui-imgbox-img>image {
  max-width: 100%;
}

.layui-imgbox-repeat {
  position: absolute;
  display: block;
  width: 32rpx;
  height: 32rpx;
  line-height: 28rpx;
  right: 2px;
  bottom: 2px;
  color: #999;
  font-size: 30rpx;
  background: #fff
}

.uploadbtn {
  position: relative;
  height: 100rpx;
  width: 100rpx
}

/* 标签容器样式 */
.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

/* 单个标签样式 */
.tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #fff;
  background-color: #cfcfcf;

}
</style>